<template>
    <div class="h100 flx-center">
        <div class="loginBox">
            <h2 class="txt-c">fvs-designer</h2>
            <el-form :model="formInfo" :rules="formRules" ref="formRef">
                <el-form-item prop="username">
                    <el-input v-model="formInfo.username" placeholder="用户名：admin / user"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="formInfo.password" placeholder="密码：123456"></el-input>
                </el-form-item>
            </el-form>
            <div>
                <el-button type="primary" @click="login(formRef)">登录</el-button>
                <el-button :loading="loading" @click="resetForm(formRef)">重置</el-button>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import type { ElForm } from "element-plus";
import { Login } from "@/interface/app";
import { useAuthStore } from '@/stores/modules/auth';
import { useTabsStore } from '@/stores/modules/tabs';
import { useKeepAliveStore } from '@/stores/modules/keepAlive';
import { initDynamicRouter } from "@/routers/dynamicRouter";
import { loginApi } from "@/api/app";
import md5 from "md5";

const router = useRouter();
const authStore = useAuthStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const formRef = ref<FormInstance>();
const formRules = reactive({
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const formInfo = reactive<Login.ReqLoginForm>({
    username: "admin",
    password: "123456"
});

const resetForm = async (formEl) => {
    if (!formEl) return
    formEl.resetFields();
}
const login = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async valid => {
        if (!valid) return;
        loading.value = true;
        try {
            // 1.执行登录接口
            const { data } = await loginApi({ ...formInfo, password: md5(formInfo.password) });
            authStore.setToken(data);

            //获取用户信息
            authStore.getUserInfo(); 

            // 2.添加动态路由
            await initDynamicRouter();

            // 3.清空 tabs、keepAlive 数据
            tabsStore.setTabs([]);
            keepAliveStore.setKeepAliveName([]);

            // 4.跳转到首页
            router.push(APP_CONFIG.HOME_URL);
        } finally {
            loading.value = false;
        }
    })
}

onMounted(() => {
    // 监听 enter 事件（调用登录）
    document.onkeydown = (e: KeyboardEvent) => {
        if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
            if (loading.value) return;
            login(formRef.value);
        }
    };
});

onBeforeUnmount(() => {
    document.onkeydown = null;
});
</script>
<style lang="scss" scoped>
.loginBox {
    width: 420px;
    margin-top: -160px;
    border-radius: 10px;
    box-shadow: rgb(0 0 0 / 10%) 0 2px 10px 2px;
    padding: 20px 40px 40px;
}
</style>